var app = getApp();
var util = require('util.js');
//路线合法性检查
function checkPathPointList(that, pathData) {
  var _pathData = [],
    error = false;
  var errText = [];
  //计算发货和收货点数量和空点数量
  for (var i = 0; i < pathData.length; i++) {
    if (pathData[i].name == 'undefined' || String(pathData[i].name).indexOf('按此输入') > -1 || pathData[i].name == '') {
      errText.push('第' + (i + 1) + '个点的名称为空');
    }
    if (pathData[i].address == 'undefined' || pathData[i].address == '') {
      errText.push('第' + (i + 1) + '个点的名称为空');
    }
  };
  if (errText.length > 0) {
    return {
      errMsg: true,
      errText: errText.join('，')
    };
  } else {
    return {
      errMsg: false,
      errText: ''
    };
  }
}
//路线计算
function calculateDistance(that, isReturn, pathData, hideLoading, callback) {
  var _from = new Array(),
    _from_i = 0,
    _to = new Array(),
    _to_i = 0;
  if (pathData.length < 2) {
    return false;
  }
  var data = {
    warehouse: "",
    shop: [],
    isReturn: isReturn,
    toPoint: ""
  };
  for (var i = 0; i < pathData.length; i++) {
    if (pathData[i].type == 'warehouse' && pathData[i].latitude) {
      data.warehouse = pathData[i].longitude + "," + pathData[i].latitude;
    }
    if (pathData[i].type == 'shop' && pathData[i].latitude) {
      data.shop.push(pathData[i].longitude + "," + pathData[i].latitude);
    }
  };
  if(isReturn){
    data.toPoint = data.warehouse
  }
  if (!hideLoading) {
    wx.showLoading({
      title: '计算里程中...',
      mask: true
    });
  }
  console.log(data)
  if (!data.warehouse || data.shop.length == 0) {
    wx.hideLoading();
    return false;
  }
  util.postData("/tencent/map/driving", data, function (res, error) {
    console.log(res.data);
    console.log(error);
    let disance = 0
    let duration = 0
    if(res.data?.result?.result?.routes?.length>0){
      disance = Number(res.data.result.result.routes[0].distance/1000).toFixed(1)
      duration = Number(res.data.result.result.routes[0].duration/60).toFixed(2)
    }
    that.setData({
      distance: disance,
      duration: duration,
      //back_distance: Number(res.data.back_distance).toFixed(1),
      //back_duration: res.data.back_duration,
      //restriction: res.data.restriction
    });
    var postData = that.data.postData;
    postData.total_mileage = disance;
    postData.total_duration = duration;
    postData.back_distance = 0;
    postData.back_duration = 0;
    that.setData({
      postData: postData
    });
    if (!hideLoading) {
      wx.hideLoading();
      setTimeout(function () {
        wx.hideLoading();
      }, 100)
    }
    if (callback) callback();
  });
  if (!hideLoading) {
    wx.hideLoading();
    setTimeout(function () {
      wx.hideLoading();
    }, 100)
  }
  if (callback) callback();
}
module.exports = {
  checkPathPointList: checkPathPointList,
  calculateDistance: calculateDistance
}